import { lib, game, ui, get, ai, _status } from "../../../noname.js";
export default {
    name: "DALF_outStory",
    character: {
        "DALF_Mayuri": ["female", "DALF_group", 5,
            ["DALF_shengtang", "DALF_caijue", "DALF_chidian"],
            []
        ],
        "DALF_REN": ["female", "DALF_group", 3,
            ["DALF_leyuan", "DALF_zhangwu"],
            []
        ],
        // "DALF_WhiteQueen": ["female", "DALF_group", 3,
        //     ["DALF_siyu", "DALF_luanzhou"],
        //     []
        // ],
        "DALF_SonogamiRinne": ["female", "DALF_group", 3,
            ["DALF_tuomeng", "DALF_zhimeng", "DALF_sumeng"],
            ["name:圆神|凛弥"]
        ],
        "DALF_ArusuMaria": ["female", "DALF_group", 3,
            ["DALF_chaosuan", "DALF_guizheng"],
            ["name:或守|鞠亚"]
        ],
        "DALF_ArusuMarina": ["female", "DALF_group", 3,
            ["DALF_hairu", "DALF_moshu"],
            ["name:或守|鞠奈"]
        ],
        "DALF_TakamiyaMana": ["female", "DALF_group", "3/4",
            ["DALF_yingfen", "DALF_jiqiang", "DALF_congyun"],
            ["name:崇宫|真那"]
        ],
        "DALF_NibelCole": ["female", "DALF_group", "0/1",
            ["DALF_qianye", "DALF_buxi", "DALF_shenshi"],
            []
        ],
    },
    characterTitle: {
        "DALF_Mayuri": "<font color=gold>雷霆圣堂</font>",
        "DALF_SonogamiRinne": "<font color=#FF69B4>凶祸乐园</font>"
    },
    translate: {
        "DALF_outStory": "别传",


        "DALF_Mayuri": "万由里",
        "DALF_shengtang": "圣堂",
        "DALF_shengtang_info": "锁定技，其他角色结束阶段，你令其获得X张【影】并明置之（X为其本回合造成的伤害值）。若X为0，其回复1点体力。",
        "DALF_caijue": "裁决",
        "DALF_caijue_info": "出牌阶段限一次，你可以弃置任意名角色手牌中明置的【影】：1.各两张；2.共五张。然后这些角色各摸一张牌。",
        "DALF_caijue_backup": "裁决",
        "DALF_chidian": "敕电",
        "DALF_chidian_info": "锁定技，结束阶段、或其他角色对你造成伤害后，你对手牌中明置【影】数不为最少的角色各造成1点雷电伤害，令这些角色各随机弃置一张【影】。",


        "DALF_REN": "莲",
        "DALF_leyuan": "乐园",
        "DALF_leyuan_info": "结束阶段或当你回复体力后，你可以将一一名角色区域内的一张牌置入另一名角色对应区域内，被移走牌的角色摸一张牌。该技能结算期间，你视为拥有〖洞察〗。",
        "DALF_zhangwu": "瘴雾",
        "DALF_zhangwu_info": "一名角色弃牌阶段开始时，你可以选择满足条件的一项：①若其手牌数大于体力值，令其弃置两张手牌，本阶段手牌上限+1；②若其已受伤，令其摸两张牌，本阶段手牌上限-1；③若其没有手牌，你选择回复1点体力或摸一张牌。",


        "DALF_WhiteQueen": "白之女王",
        "DALF_luanzhou": "銮昼",
        "DALF_luanzhou_info": "锁定技，每名角色游戏开始时，为没有〔王国宝物〕的其临时创建一张♠A【空无】，装备在额外的宝物栏并锁定之。你的〔王国宝物〕不会降格、只要不是【空无】便只能在Q时升变为♥Q【女王】。",
        "DALF_KingdomTreasure_upgrade": "升变",
        "DALF_KingdomTreasure_upgrade_info": "将为〔王国宝物〕的此牌转化为指定的另一种〔王国宝物〕且相应修改此牌点数。<br>" +
            "升变检定时，若该〔王国宝物〕为【空无】，则升变为【士兵】。<br>若为【士兵】且点数为8~10，则装备者从下述三种选一升变：<br>" +
            " ♠8【主教】| ♠9【骑士】|♠10【城堡】<br>" +
            "点数大于10，则依照点数按下述规则升变：<br>" +
            "J->【王子】| Q->【女王】| K->【国王】<br>" +
            "每次升变为装备者加1点体力上限并回复所有体力。<br>" +
            "若升变结果为【国王】且场上已存在【国王】，则改为从前四种中自由选择升变结果。",
        "DALF_KingdomTreasure_relegate": "降格",
        "DALF_KingdomTreasure_relegate_info": "将为〔王国宝物〕的此牌转化为级别更低的〔王国宝物〕。" +
            "降格检定时，若此牌点数小于8，则失去所有不因【士兵】升变而获得的体力上限，然后降格为【士兵】；为A，则再减1点体力上限，改为降格为♠【空无】。",
        "DALF_siyu": "司宇",
        "DALF_siyu_info": "出牌阶段限一次，你可以弃置一张基本牌，从牌堆中获得一张【前进】。你使用的【前进】、或对应实体牌中含【前进】的牌多结算一次。",


        "DALF_SonogamiRinne": "圆神凛弥",
        "DALF_tuomeng": "拓梦",
        "DALF_tuomeng_info": "锁定技，准备阶段和结束阶段，若X不大于体力值，你令一名其他角色获得「虚幻」标记，否则你移去一名角色的「虚幻」。然后有「虚幻」的角色各将一张手明置。（X为有「虚幻」的角色数）",
        "DALF_zhimeng": "织梦",
        "DALF_zhimeng_info": "锁定技，有/无「虚幻」的其他角色回合开始时，所有无/有「虚幻」、且没有本技能的角色进入【调虎离山】效果（本回合视为被移出游戏）。",
        "DALF_sumeng": "溯梦",
        "DALF_sumeng_info": "当你需要使用或打出除【无懈可击】以外的即时牌时，你可以令有「虚幻」的其他角色选择是否展示一张此牌。若有角色响应，你使用或打出此牌，其摸一张牌；没有，则你摸一张牌，该技能本回合失效。",
        "DALF_sumeng_append": "<span style='font-family: yuanli'>若响应的角色因〖织梦〗或其它技能效果被移出游戏，则在此结算中暂时回到游戏</span>",


        "DALF_ArusuMaria": "或守鞠亚",
        "DALF_chaosuan": "超算",
        "DALF_chaosuan_info": "锁定技，牌堆顶的牌对你可见。你可以如手牌般使用或打出此牌。",
        "DALF_guizheng": "椝整",
        "DALF_guizheng_info": "出牌阶段，你可以弃置X张牌，并令一名其他角色重铸一张手牌。（X为本阶段该技能此前的发动次数）",


        "DALF_ArusuMarina": "或守鞠奈",
        "DALF_hairu": "骇入",
        "DALF_hairu_info": "出牌阶段限一次，你可以观看任意名角色的手牌，各记录其中一张牌为「骇入」（记录不会消失且对所有角色可见）。",
        "DALF_moshu": "模数",
        "DALF_moshu_info": "锁定技，其他角色使用牌时，若对应实体牌中有「骇入」牌，此牌对你无效，随机记录牌堆中三张牌为「骇入」；没有、且均来自手牌区、且其手牌中有「骇入」牌，你获得该「骇入」牌，若此时在其回合内，使用的牌作废。",


        "DALF_TakamiyaMana": "崇宫真那",
        "DALF_yingfen": "鹰芬",
        "DALF_yingfen_info": "锁定技，你到其他角色距离-X（X为你已损失体力值-其已损失体力值，至少为0）；若你体力值为1，你的手牌上限+3。",
        "DALF_jiqiang": "激锵",
        "DALF_jiqiang_info": "锁定技，每名角色结束阶段，若你手牌数小于体力值，你失去1点体力并将手牌摸至体力上限。",
        "DALF_congyun": "从云",
        "DALF_congyun_info": "你使用【杀】被闪避后、或你闪避【杀】后，你可以弃置一张非基本牌，回复1点体力。",


        "DALF_NibelCole": "尼别科尔",
        "DALF_qianye": "千页",
        "DALF_qianye_info": "锁定技，你跳过弃牌阶段；游戏开始时，你获得角色数张【影】。" +
            "<br>当你回复体力时，防止之并获得两张【影】。" +
            "<br>你的回合内，当一张红色牌进入弃牌堆时，你获得一张【影】。",
        "DALF_buxi": "不息",
        "DALF_buxi_info": "锁定技，当你受到伤害时，防止之，伤害来源弃置你伤害值两倍的手牌。" +
            "<br>若你失去手牌中所有【影】，你进入濒死状态；否则防止你处于濒死状态。",
        "DALF_shenshi": "神蚀",
        "DALF_shenshi_info": "出牌阶段各限一次，你可以将一张黑色手牌当〔刺【杀】/【过河拆桥】〕使用。",

    },
    /** @type { importCharacterConfig['skill'] } */
    skill: {
        /*万由里*/
        "DALF_shengtang": {
            audio: "ext:约会大作战/audio:2",
            trigger: {
                global: "phaseJieshu",
            },
            forced: true,
            filter(event, player) {
                if (event.player == player) return false;
                return event.player.isDamaged() ||
                    event.player.getHistory('sourceDamage').length > 0;
            },
            logTarget: "player",
            async content(event, trigger, player) {
                let num = 0;
                trigger.player.getHistory('sourceDamage', evt => {
                    num += evt.num;
                });
                if (num > 0) {
                    const yingCards = lib.card.ying.getYing(num);
                    await trigger.player.gain(yingCards, 'gain2');
                    await trigger.player.addShownCards(yingCards, 'visible_DALF');
                } else {
                    trigger.player.recover();
                }
            }
        },
        "DALF_caijue": {
            audio: "ext:约会大作战/audio:1",
            enable: "phaseUse",
            usable: 1,
            filter(event, player) {
                let count = 0;
                for (const current of game.players) {
                    const yings = current.countDiscardableCards(player, 'h', card => {
                        return get.is.shownCard(card) && get.name(card) == 'ying';
                    });
                    if (yings > 1) return true;
                    count += yings;
                    if (count >= 5) return true;
                }
                return false;
            },
            chooseButton: {
                dialog(event, player) {
                    let dialog = ui.create.dialog('裁决', 'hidden'), map = {};
                    dialog.addText('弃置任意名角色各两张【影】、或共计五张【影】');
                    game.players.forEach(current => {
                        const yingCards = current.getDiscardableCards(player, 'h', card => {
                            return get.is.shownCard(card) && get.name(card) == 'ying';
                        });
                        if (!map[yingCards.length]) map[yingCards.length] = [];
                        map[yingCards.length].push(current);
                        if (yingCards.length > 0) {
                            dialog.addText(get.translation(current) + '的【影】');
                            dialog.add(yingCards);
                        }
                    });
                    lib.skill['DALF_caijue'].aiCheck(dialog.buttons, map, player);
                    return dialog;
                },
                select: [1, Infinity],
                check(button) {
                    return button.value || -1;
                },
                filterOk() {
                    const buttons = ui.selected.buttons;
                    if (buttons.length == 5) return true;
                    let countsMap = {};
                    for (const button of buttons) {
                        const owner = get.owner(button.link);
                        if (!countsMap[owner.playerid])
                            countsMap[owner.playerid] = 1;
                        else countsMap[owner.playerid]++;
                        if (countsMap[owner.playerid] > 2) return false;
                    }
                    for (const i in countsMap)
                        if (countsMap[i] < 2) return false;
                    return true;
                },
                backup(links, player) {
                    return {
                        audio: "DALF_caijue",
                        filterCard() { return false },
                        selectCard: -1,
                        cards: links,
                        delay: false,
                        async content(event, trigger, player) {
                            "step 0"
                            const cards = lib.skill['DALF_caijue_backup'].cards;
                            let pairs = {};
                            cards.forEach(card => {
                                const owner = get.owner(card);
                                if (!pairs[owner.playerid])
                                    pairs[owner.playerid] = [owner, [card]];
                                else
                                    pairs[owner.playerid][1].push(card);
                            })
                            for (const i in pairs)
                                await pairs[i][0].discard(pairs[i][1])
                                    .set('delay', false);
                            for (const i in pairs)
                                await pairs[i][0].draw()
                                    .set('delay', false);
                        },
                        ai: {
                            order: 10,
                            result: {
                                player: 1
                            }
                        }
                    };
                }
            },
            ai: {
                order: 1,
                threaten: 1.7,
                result: {
                    player: 1
                }
            },
            aiCheck(buttons, ranks, player) {
                //当发动【裁决】的角色拥有技能【敕电】时
                if (player.hasSkill('DALF_chidian')) {
                    //sort升序排列（从小到大）
                    let keys = Object.keys(ranks).map(Number).sort((a, b) => a - b);
                    let friends = game.filterPlayer(current => {
                        return player.attitudeTo(current) > 0;
                    });
                    //当仅有两种数量
                    //且该种数量为2时
                    //或有两种数量
                    //且最大值和最小值的差值为2时
                    if ((keys.length == 1 && keys[0] == 2) ||
                        (keys.length == 2 && keys[1] - keys[0] == 2)) {
                        //策略为：只弃置友方角色各两张【影】
                        let countChoices = {};
                        buttons.forEach(button => {
                            const owner = get.owner(button.link);
                            if (friends.includes(owner)) {
                                if (!countChoices[owner.playerid])
                                    countChoices[owner.playerid] = 2;
                                if (countChoices[owner.playerid]-- > 0)
                                    button.value = 2;
                            }
                        });
                    } else { //无法执行“仅弃置友方角色各两张【影】”的策略时
                        //策略为：弃置共计五张【影】
                        //优先将体力最小的友方的【影】弃置至最少
                        //其次弃置体力最多的角色的【影】补齐五张
                        let buttonList = [], tbMap = {};
                        buttons.forEach(button => {
                            const owner = get.owner(button.link);
                            if (tbMap[owner.playerid] === undefined) {
                                tbMap[owner.playerid] = 0;
                                for (const i in ranks) {
                                    if (ranks[i].includes(owner)) {
                                        tbMap[owner.playerid] = Number(i) - keys[0];
                                        break;
                                    }
                                }
                            }
                            if (tbMap[owner.playerid] > 0) {
                                tbMap[owner.playerid]--;
                                button.value = friends.includes(owner) ?
                                    (10 - Math.min(owner.hp, 5)) :
                                    (Math.min(owner.hp, 5));
                                button.ownerid = owner.playerid;
                                buttonList.push(button);
                            }
                        });
                        buttonList.sort((a, b) => b.value - a.value);
                        function* generateArray(list, map) {
                            let index = 0, playerids = [];
                            if (map[0].length >= buttonList.length) index = 6;
                            else {
                                for (const button of map[0])
                                    if (button?.ownerid)
                                        playerids.add(button.ownerid);
                                for (const playerid of playerids)
                                    index += tbMap[Number(playerid)];
                            }
                            if (index >= 5) {
                                yield [[], index == 5 ? 1 : 0];
                            } else {
                                for (let i = 0; i <= list.length; i++) {
                                    map[0].push(list[i]);
                                    for (const item of generateArray(list.slice(i + 1), map)) {
                                        yield [[list[i], ...item[0]], 0 + item[1]];
                                    }
                                    map[0].pop();
                                }
                            }
                        };
                        let plans = [];
                        for (const plan of generateArray(buttonList, [[], 0])) {
                            let value = plan[1] * 50;
                            plan[0].forEach(button => {
                                if (button?.value) value += button.value;
                            });
                            plans.push([plan[0], value]);
                        }
                        plans.sort((a, b) => b[1] - a[1]);
                        plans = plans[0];
                        if (plans[0].length < 5) {
                            let pbMap = {};
                            plans[0].forEach(button => {
                                const ownerid = get.owner(button.link).playerid;
                                if (!pbMap[ownerid]) pbMap[ownerid] = {
                                    value: button.value,
                                    buttons: [button]
                                };
                                else pbMap[ownerid].buttons.push(button);
                            });
                            for (const i in pbMap) {
                                if (pbMap[i].value <= 5) plans[0].removeArray(pbMap[i].buttons);
                                else if (pbMap[i].buttons.length % 2 != 0)
                                    plans[0].remove(pbMap[i].buttons[0]);
                            }
                        }
                        buttonList.forEach(button => {
                            if (!plans[0].includes(button))
                                delete button.value;
                            delete button.ownerid;
                        });
                    }
                } else { //没有技能【敕电】时
                    let value = 0, previous;
                    for (const button of buttons) {
                        const owner = get.owner(button.link);
                        if (owner != previous) {
                            previous = owner;
                            value = 1;
                        } else value++;
                        button.value = player.attitudeTo(owner) > 0 ? value : 0;
                    }
                }
            },
        },
        "DALF_chidian": {
            audio: "ext:约会大作战/audio:2",
            trigger: {
                player: ["phaseJieshu", "damageEnd"]
            },
            forced: true,
            filter: function (event, player) {
                if (event.name == 'damage' && event.source == player) return false;
                const yings = game.players[0].countCards('h', card => {
                    return get.is.shownCard(card) && get.name(card) == 'ying';
                });
                for (let i = 1; i < game.players.length; i++) {
                    if (game.players[i].countCards('h', card => {
                        return get.is.shownCard(card) && get.name(card) == 'ying';
                    }) != yings) return true;
                }
                return false;
            },
            async content(event, trigger, player) {
                "step 0"
                let pairs = [], min = Infinity;
                game.players.forEach(current => {
                    const yings = current.countCards('h', card => {
                        return get.is.shownCard(card) && get.name(card) == 'ying';
                    });
                    pairs.push([current, yings]);
                    if (min > yings) min = yings;
                });
                for (const i of pairs) {
                    if (i[1] == min) break;
                    await i[0].damage('thunder');
                }
                for (const i of pairs) {
                    if (i[1] == min) break;
                    const yingCards = i[0].getCards('h', card => {
                        return get.name(card) == 'ying';
                    }).randomGets(1);
                    if (yingCards.length)
                        i[0].discard(yingCards, 'notBySelf')
                            .set('delay', false);
                }
            },
            ai: {
                effect: {
                    target: function (card, source, player) {
                        if (source == player) return [1, 0];
                        if (source.hasSkillTag('jueqing', false, player)) return [1, -1];
                        let pairs = [], min = Infinity, value = 0;
                        game.players.forEach(current => {
                            const yings = current.countCards('h', card => {
                                return get.is.shownCard(card) && get.name(card) == 'ying';
                            });
                            pairs.push([current, yings]);
                            if (min > yings) min = yings;
                        });
                        for (const i of pairs) {
                            if (i[1] > min) value += (i[0].hp > 1 ? 1 : 2) *
                                (source.attitudeTo(i[0]) > 0 ? -1 : 1);
                        }
                        return [1.125, value];
                    }
                }
            }
        },

        /*莲*/
        "DALF_leyuan": {
            audio: "ext:约会大作战/audio:2",
            trigger: {
                player: ["phaseJieshu", "recoverAfter"],
            },
            //frequent:true,
            filter: function (event, player) {
                return game.hasPlayer(function (current) {
                    return current.countCards('hej');
                });
            },
            content: function () {
                "step 0"
                if (!player.hasSkill('akiko_dongcha')) {
                    event.getDongcha = true;
                    player.addTempSkill('akiko_dongcha');
                }
                var next = player.chooseTarget(true);
                next.filterTarget = function (card, player, target) {
                    return target.countCards('hej');
                };
                next.ai = function (target) {
                    if (get.attitude(_status.event.player, target) > 0) {
                        return target.countCards('he', function (card) {
                            return get.value(card) < 1;
                        }) || target.countCards('j');
                    } else return target.countCards('he', function (card) {
                        return get.value(card) >= 6;
                    });
                    return 1;
                };
                next.set('prompt', '请选择被拿走牌的角色');
                "step 1"
                if (result.bool) {
                    event.target1 = result.targets[0];
                    player.choosePlayerCard(event.target1, 1, true).set('ai', function (button) {
                        if (get.attitude(_status.event.player, event.target1) > 0) {
                            if (event.target1.countCards('j')) return get.position(button.link) == 'j';
                            return 1 - get.value(button.link);
                        }
                        if (get.position(button.link) == 'j') return -1;
                        return get.value(button.link);
                    }).set('position', 'hej');
                } else event.finish();
                "step 2"
                if (result.bool) {
                    event.card1 = result.links[0];
                    var tip = '请将' + get.translation(event.card1) + '置入另一名角色的';
                    switch (get.position(event.card1)) {
                        case 'h':
                            tip += '手牌区内';
                            break;
                        case 'e':
                            tip += '装备区内';
                            break;
                        case 'j':
                            tip += '判定区内';
                            break;
                    }
                    player.chooseTarget(tip, true).set('ai', function (target) {
                        var card = result.links[0];
                        var att = get.attitude(_status.event.player, target);
                        if (get.position(card) == 'j') return -att;
                        if (get.value(card, target) > 0) return att > 0;
                        return -att;
                    }).set('filterTarget', function (card, player, target) {
                        return event.target1 != target;
                    });
                }
                "step 3"
                if (result.bool) {
                    var target2 = result.targets[0];
                    switch (get.position(event.card1)) {
                        case 'j':
                            {
                                event.target1.$give(card, target2);
                                if (event.card1.viewAs)
                                    target2.addJudge({ name: event.card1.viewAs }, [event.card1]);
                                else
                                    target2.addJudge(event.card1);
                                break;
                            }
                        case 'e':
                            {
                                event.target1.$give(card, target2);
                                target2.equip(event.card1);
                                break;
                            }
                        default:
                            target2.gain(event.card1, 'giveAuto');
                            break;
                    }
                    event.target1.draw();
                }
                "step 4"
                if (event.getDongcha) player.removeSkill('akiko_dongcha');
            },
            derivation: ["akiko_dongcha"]
        },
        "DALF_zhangwu": {
            audio: "ext:约会大作战/audio:2",
            trigger: {
                global: "phaseDiscardBegin",
            },
            direct: true,
            filter: function (event, player, onrewrite) {
                //if(event.player==player) return true;
                if (event.player.countCards('h') > event.player.hp) return true;
                if (event.player.isDamaged()) return true;
                if (!event.player.countCards('h')) return true;
                return false;
            },
            content: function () {
                "step 0"
                var list = [];
                var listBan = [0, 1, 2];
                if (trigger.player.countCards('h') > trigger.player.hp) {
                    list.add('令' + get.translation(trigger.player) + '弃两张牌，本阶段手牌上限+1');
                    listBan.remove(0);
                }
                if (trigger.player.isDamaged()) {
                    list.add('令' + get.translation(trigger.player) + '摸两张牌，本阶段手牌上限-1');
                    listBan.remove(1);
                }
                if (!trigger.player.countCards('h')) {
                    list.add('令你自己摸一张牌或回复一点体力');
                    listBan.remove(2);
                }
                event.list = listBan;
                var next = player.chooseControl('cancel2');
                next.set('choiceList', list);
                next.ai = function () {
                    var buttonSelect = function (cho, list) {
                        var num = 0;
                        if (list.includes(cho)) return 'cancel2';
                        if (list.length > 0) {
                            for (var i = 0; i <= 2; i++) {
                                if (cho >= i && list.includes(i)) num++;
                                //if(cho<i||!list.includes(i)) continue;
                            }
                        }
                        return cho - num;
                    };
                    var player = _status.event.player;
                    var target = _status.event.getTrigger().player;
                    var num = target.needsToDiscard();
                    var list = _status.event.listBan;
                    if (get.attitude(player, target) > 0) {
                        if (num > 2) return buttonSelect(0, list);
                    } else {
                        if (num > 2) return buttonSelect(1, list);
                        return buttonSelect(0, list);
                    }
                    return buttonSelect(2, list);
                };
                next.set('prompt', get.prompt('DALF_zhangwu'));
                next.set('listBan', listBan);
                "step 1"
                if (result.control != 'cancel2' && [0, 1, 2].includes(result.index)) {
                    player.logSkill('DALF_zhangwu', trigger.player);
                    var cho = result.index;
                    for (var i = cho; i < event.list.length; i++) {
                        if (event.list.includes(cho)) cho++;
                    }
                    switch (cho) {
                        case 0:
                            {
                                trigger.player.chooseToDiscard(2, 'h', true);
                                trigger.player.addTempSkill('DALF_zhangwu_limitAdd', { player: 'phaseDiscardEnd' });
                                break;
                            }
                        case 1:
                            {
                                trigger.player.draw(2);
                                trigger.player.addTempSkill('DALF_zhangwu_limitSub', { player: 'phaseDiscardEnd' });
                                break;
                            }
                        case 2:
                            {
                                player.chooseDrawRecover(1, 1, true);
                                break;
                            }
                    }
                }
            },
            subSkill: {
                limitAdd: {
                    mod: {
                        maxHandcard: function (player, num) {
                            return num + 1;
                        }
                    },
                    sub: true
                },
                limitSub: {
                    mod: {
                        maxHandcard: function (player, num) {
                            return num - 1;
                        }
                    },
                    sub: true
                }
            }
        },

        /*白之女王*/
        "DALF_luanzhou": {
            audio: "ext:约会大作战/audio:2",
            trigger: {
                global: ["phaseBefore", "enterGame"]
            },
            forced: true,
            filter: function (event, player) {
                return event.name != 'phase' || game.phaseNumber == 0;
            },
            content: function () {
                "step 0"
                game.addGlobalSkill('DALF_KingdomTreasure');
                game.countPlayer(function (current) {
                    if (current.storage['DALF_KingdomTreasure'] != undefined)
                        return false;
                    current.expandEquip(5);
                    let cardx = game.createCard({
                        name: 'DALF_card_nothing',
                        suit: 'spade',
                        number: 1
                    });
                    current.storage['DALF_KingdomTreasure'] = cardx;
                    current.equip(cardx);
                    if (!cardx.storage)
                        cardx.storage = {};
                    if (!cardx.storage.gainMaxHp)
                        cardx.storage.gainMaxHp = 0;
                    current.storage['DALF_card_pawn_2'] = 0;
                    cardx.classList.add('emptyequip');
                    //cardx.classList.add('hidden');
                });
                "step 1"
                if (trigger.name == 'phase')
                    lib.inpile.addArray(['DALF_card_forward', 'DALF_card_usurp']);
            },
            derivation: ["DALF_KingdomTreasure_upgrade", "DALF_KingdomTreasure_relegate"],
        },
        "DALF_KingdomTreasure": {
            charlotte: true,
            mod: {
                canBeGained: function (card, source, player) {
                    if (player.storage['DALF_KingdomTreasure'] == card)
                        return false;
                },
                canBeDiscarded: function (card, source, player) {
                    if (player.storage['DALF_KingdomTreasure'] == card)
                        return false;
                },
                canBeReplaced: function (card, player) {
                    if (player.storage['DALF_KingdomTreasure'] == card)
                        return false;
                },
                cardname: function (card, owner) {
                    if (owner.storage['DALF_KingdomTreasure'] == card)
                        return card.name;
                },
                cardnature: function (card, owner) {
                    if (owner.storage['DALF_KingdomTreasure'] == card)
                        return false;
                },
                cardDiscardable: function (card, player) {
                    if (player.storage['DALF_KingdomTreasure'] == card)
                        return false;
                },
                cardEnabled2: function (card, player) {
                    if (player.storage['DALF_KingdomTreasure'] == card)
                        return false;
                }
            },
            trigger: { player: ["loseBefore", "disableEquipBefore", "die", "dyingAfter"] },
            forced: true,
            priority: 3,
            forceDie: true,
            filter: function (event, player) {
                let card = player.storage['DALF_KingdomTreasure'];
                if (card == undefined) return false;
                if (event.name == 'die') {
                    return card.classList.includes('emptyequip');
                }
                if (event.name == 'dying') {
                    return !card.classList.includes('emptyequip');
                }
                if (event.name == 'disableEquip') {
                    if (player.countEnabledSlot('equip5') == 1)
                        return event.slots.includes('equip5');
                    return false;
                }
                return !card.storage.isOnChanged && event.cards.includes(card);
            },
            content: function () {
                if (trigger.name == 'lose') {
                    trigger.cards.remove(player.storage['DALF_KingdomTreasure']);
                } else if (trigger.name == 'die') {
                    player.storage['DALF_KingdomTreasure'].classList.remove('emptyequip');
                } else if (trigger.name == 'dying') {
                    player.storage['DALF_KingdomTreasure'].classList.add('emptyequip');
                } else {
                    while (trigger.slots.includes('equip5'))
                        trigger.slots.remove('equip5');
                }
            },
            subSkill: {
                upgrade: {
                    content: function () {
                        "step 0"
                        event.isUpgrade = false;
                        event.number = get.number(card);
                        if (card.name == 'DALF_card_nothing') {
                            if (event.number > 1) {
                                card.name = 'DALF_card_pawn';
                                card.storage.gainMaxHp += 1;
                                player.gainMaxHp(1);
                                game.log(player, '的', '#g【空无】', '升变为了', '#g【士兵】');
                                event.isUpgrade = true;
                            }
                        }
                        if (event.number < 8) event.goto(4);
                        "step 1"
                        if (player.hasSkill('DALF_luanzhou')) {
                            if (event.number >= 12 && card.name != 'DALF_card_queen2') {
                                card.name = 'DALF_card_queen2';
                                card.suit = 'heart';
                                card.storage.gainMaxHp += 2;
                                player.gainMaxHp(2);
                                game.log(player, '的', '#g【士兵】', '升变为了', '#g【女王】');
                                event.isUpgrade = true;
                            }
                            event.goto(4);
                        }
                        "step 2"
                        var map = {
                            13: 'DALF_card_king',
                            12: 'DALF_card_queen',
                            11: 'DALF_card_prince',
                            10: 'DALF_card_rook',
                            9: 'DALF_card_knight',
                            8: 'DALF_card_bishop'
                        };
                        var list = [map[8], map[9], map[10]],
                            needChoise = false;
                        if (event.number < 11) {
                            if (card.name == 'DALF_card_pawn') needChoise = true;
                            else return card.name;
                        } else if (event.number >= 13 && game.hasPlayer(function (current) {
                            return current.storage['DALF_KingdomTreasure'].name ==
                                'DALF_card_king';
                        })) {
                            list.push('DALF_card_prince');
                            needChoise = true
                        }
                        if (needChoise) {
                            for (let i = 0; i < list.length; i++) {
                                list[i] = ['equip5', i + 8, list[i]];
                            }
                            var next = player.chooseButton([
                                '请为〔王国宝物〕选择升变对象', [list, 'vcard']
                            ]);
                            next.set('ai', function (button) {
                                if (button.link[1] == 11) return 10;
                                var player = _status.event.player;
                                if (player.countCards('hs', function (card) {
                                    return get.name(card) == 'DALF_card_forward';
                                }) + player.storage['DALF_KingdomTreasure'].number > 10)
                                    return 0;
                                switch (button.link[1]) {
                                    case 8:
                                        return player.countCards('hs');
                                    case 9:
                                        return 3;
                                    case 10:
                                        return player.hp + 1;
                                }
                                return 0;
                            });
                            next.set('forced', event.number >= 13);
                        } else event._result = {
                            links: [
                                ['equip5', event.number, map[event.number]]
                            ],
                            bool: true
                        };
                        "step 3"
                        if (result.bool) {
                            var name = result.links[0][2];
                            var tranA = '【' + get.translation(card.name) + '】',
                                tranB = '【' + get.translation(name) + '】';
                            card.name = name;
                            card.number = result.links[0][1];
                            card.storage.gainMaxHp += 1;
                            player.gainMaxHp(1);
                            game.log(player, '的', '#g' + tranA, '升变为了', '#g' + tranB);
                            event.isUpgrade = true;
                        }
                        "step 4"
                        if (event.isUpgrade) {
                            card.storage.isOnChanged = true;
                            var num = player.maxHp - player.hp;
                            if (num > 0) player.recover(num);
                            game.cardsGotoOrdering(card);
                        }
                        card.init(card);
                        "step 5"
                        if (event.isUpgrade) {
                            delete card.storage.isOnChanged;
                            player.equip(card);
                        }
                        return card.name;
                    },
                    sub: true
                },
                relegate: {
                    content: function () {
                        "step 0"
                        event.isRelegate = false;
                        if (!player.hasSkill('DALF_luanzhou')) {
                            var tranA = '【' + get.translation(card.name) + '】';
                            if (card.number == 1) {
                                if (card.name != 'DALF_card_nothing') {
                                    var num = card.storage.gainMaxHp;
                                    card.name = 'DALF_card_nothing';
                                    card.storage.gainMaxHp = 0;
                                    if (num > 0) player.loseMaxHp(num);
                                    game.log(player, '的', '#g' + tranA, '降格为了', '#g【空无】');
                                    event.isRelegate = true;
                                }
                            } else if (card.number < 8 && card.name != 'DALF_card_pawn') {
                                var num = card.storage.gainMaxHp - 1;
                                card.name = 'DALF_card_pawn';
                                card.storage.gainMaxHp = 1;
                                if (num > 0) player.loseMaxHp(num);
                                game.log(player, '的', '#g' + tranA, '降格为了', '#g【士兵】');
                                event.isRelegate = true;
                            } else {
                                var number2 = {
                                    'DALF_card_king': 13,
                                    'DALF_card_queen': 12,
                                    'DALF_card_prince': 11,
                                    'DALF_card_rook': 10,
                                    'DALF_card_knight': 9,
                                    'DALF_card_bishop': 8
                                }[card.name];
                                if (number2 && number2 > card.number) {
                                    switch (card.number) {
                                        case 12:
                                            card.name = 'DALF_card_queen';
                                            break;
                                        case 11:
                                            card.name = 'DALF_card_prince';
                                            break;
                                        case 10:
                                            card.name = 'DALF_card_rook';
                                            break;
                                        case 9:
                                            card.name = 'DALF_card_knight';
                                            break;
                                        case 8:
                                            card.name = 'DALF_card_bishop';
                                            break;
                                        default:
                                            card.name = 'DALF_card_pawn';
                                    }
                                    game.log(player, '的', '#g' + tranA, '降格为了', '#g【' + get.translation(card.name) + '】');
                                    event.isRelegate = true;
                                }
                            }
                        }
                        "step 1"
                        if (event.isRelegate) {
                            card.storage.isOnChanged = true;
                            game.cardsGotoOrdering(card);
                        }
                        card.init(card);
                        "step 2"
                        if (event.isRelegate) {
                            delete card.storage.isOnChanged;
                            player.equip(card);
                        }
                        return card.name;
                    },
                    sub: true
                }
            }
        },
        "DALF_siyu": {
            audio: "ext:约会大作战/audio:2",
            enable: "phaseUse",
            usable: 1,
            filter: function (event, player) {
                return player.hasCard(card => get.type(card) == 'basic', 'h');
            },
            filterCard: { type: "basic" },
            check: function (card) {
                if (get.name(card) == 'DALF_card_forward' ||
                    card.name == 'DALF_card_forward') return 0;
                return 6.5 - get.value(card);
            },
            content: function () {
                "step 0"
                var cardx = get.cardPile2('DALF_card_forward');
                if (cardx) player.gain(cardx, 'draw2');
            },
            ai: {
                order: 1,
                result: { player: 1 }
            },
            group: ["DALF_siyu_doubleUse"],
            subSkill: {
                doubleUse: {
                    trigger: { player: "useCard" },
                    forced: true,
                    filter: function (event, player) {
                        if (event.card.name == 'DALF_card_forward') return true;
                        if (event.cards && event.cards.length)
                            for (let i = 0; i < event.cards.length; i++)
                                if (event.cards[i].name == 'DALF_card_forward')
                                    return true;
                        return false;
                    },
                    content: function () {
                        "step 0"
                        trigger.effectCount++;
                    },
                    sub: true
                }
            }
        },

        /*圆神凛弥*/
        "DALF_mark_xuhuan": {
            marktext: "幻",
            intro: {
                name: "虚幻",
                markcount: () => 0
            }
        },
        "DALF_tuomeng": {
            audio: "ext:约会大作战/audio:2",
            trigger: {
                player: ["phaseZhunbei", "phaseJieshu"]
            },
            forced: true,
            content: function () {
                "step 0"
                var next = player.chooseTarget(true);
                next.set('prompt', '拓梦');
                var countMark = game.countPlayer(function (current) {
                    return current.hasMark('DALF_mark_xuhuan');
                });
                if (countMark > player.hp) {
                    next.set('filterTarget', function (card, player, target) {
                        return target.hasMark('DALF_mark_xuhuan');
                    });
                    next.set('ai', function (target) {
                        var att = Math.min(Math.max(get.attitude2(target), -10), 10);
                        return att / Math.max(target.countCards('h'), 0.5);
                    });
                    next.set('prompt2', '移去一名角色的「虚幻」标记');
                } else {
                    next.set('filterTarget', function (card, player, target) {
                        return target != player && !target.hasMark('DALF_mark_xuhuan');
                    });
                    next.set('prompt2', '令一名其他角色获得「虚幻」标记');
                    if (!countMark && trigger.name == 'phaseZhunbei') {
                        next.set('ai', function (target) {
                            return get.attitude2(target);
                        });
                    } else {
                        next.set('ai', function (target) {
                            var att = get.attitude2(target);
                            if (_status.event.hasEnemy)
                                return att;
                            return -att;
                        });
                        next.set('hasEnemy', game.hasPlayer(function (current) {
                            return current.hasMark('DALF_mark_xuhuan') &&
                                player.attitudeTo(current) <= 0;
                        }));
                    }
                }
                "step 1"
                if (result.bool) {
                    var target = result.targets[0];
                    if (target.hasMark('DALF_mark_xuhuan'))
                        target.removeMark('DALF_mark_xuhuan', 1);
                    else
                        target.addMark('DALF_mark_xuhuan', 1);
                    player.line(target);
                }
                "step 2"
                event.players = game.filterPlayer(function (current) {
                    return current.hasMark('DALF_mark_xuhuan');
                }).sortBySeat(player);
                if (!event.players.length) event.finish();
                "step 3"
                event.target = event.players.shift();
                if (event.target.hasCard(card => !get.is.shownCard(card), 'h')) {
                    var next = event.target.chooseCard('h', true);
                    next.set('filterCard', function (card) {
                        return !get.is.shownCard(card);
                    });
                    next.set('ai', function (card) {
                        return get.is.instantCard(card) ? Math.random() : 0.2;
                    });
                    next.set('prompt', '拓梦');
                    next.set('prompt2', '请选择一张手牌明置');
                } else event._result = { bool: false };
                "step 4"
                if (result.bool) {
                    event.target.addShownCards(result.cards, 'visible_DALF');
                }
                if (event.players.length) event.goto(3);
            }
        },
        "DALF_zhimeng": {
            audio: "ext:约会大作战/audio:2",
            trigger: {
                global: "phaseBegin"
            },
            forced: true,
            filter: function (event, player) {
                return event.player != player;
            },
            content: function () {
                "step 0"
                var bool = trigger.player.hasMark('DALF_mark_xuhuan');
                game.countPlayer(function (current) {
                    if (current.hasMark('DALF_mark_xuhuan') != bool &&
                        !current.hasSkill('DALF_zhimeng'))
                        current.addTempSkill('diaohulishan');
                });
            }
        },
        "DALF_sumeng": {
            audio: "ext:约会大作战/audio:2",
            enable: ["chooseToUse", "chooseToRespond"],
            forceOut: true,
            filter: function (event, player) {
                if (!game.players.some(function (current) {
                    return current != player &&
                        current.hasMark('DALF_mark_xuhuan');
                })) return false;
                for (let i of lib.inpile) {
                    if (i == 'wuxie' || !get.is.instantCard(i)) continue;
                    if (event.filterCard({ name: i }, player, event)) return true;
                }
                return false;
            },
            hiddenCard: function (player, name) {
                if (name == 'wuxie' || !get.is.instantCard(name)) return false;
                return game.players.some(function (current) {
                    return current != player &&
                        current.hasMark('DALF_mark_xuhuan') &&
                        current.countCards('h');
                });
            },
            chooseButton: {
                dialog: function (event, player) {
                    var list = [];
                    for (var i of lib.inpile) {
                        if (i == 'wuxie' || !get.is.instantCard(i))
                            continue;
                        if (event.filterCard({ name: i }, player, event))
                            list.push([get.type(i), '', i]);
                    }
                    return ui.create.dialog('溯梦', [list, 'vcard']);
                },
                check: function (button) {
                    var player = _status.event.player,
                        event = _status.event.getParent(),
                        card = { name: button.link[2] };
                    if (event.type == 'dying' && player.attitudeTo(event.dying) < 0)
                        return 0;
                    if (player.getUseValue(card, true, true) < 0) return 0;
                    let known = 1;
                    if (game.players.some(function (current) {
                        return current != player &&
                            current.hasMark('DALF_mark_xuhuan') &&
                            player.attitudeTo(current) > 0 &&
                            current.hasCard(function (cardx) {
                                if (cardx.name == card.name) {
                                    if (cardx.isKnownBy(player))
                                        known = get.useful(cardx, player) / 2;
                                    return true;
                                }
                            }, 'h');
                    })) return known;
                    return Math.random() * 2;
                },
                backup: function (links, player) {
                    return {
                        filterCard: () => false,
                        selectCard: -1,
                        viewAs: {
                            name: links[0][2],
                            suit: 'none',
                            number: null
                        },
                        precontent: function () {
                            player.logSkill('DALF_sumeng', game.players.filter(function (current) {
                                return current != player &&
                                    current.hasMark('DALF_mark_xuhuan');
                            }), false);
                        },
                        ignoreMod: true
                    };
                },
                /*
                prompt:function(links,player){
                    if(_status.event.name=='chooseToRespond')
                        return '请有「虚幻」的角色替你打出【'+get.translation(links[0][2])+'】';
                    return '请选择有「虚幻」的角色替你使用【'+get.translation(links[0][2])+'】的目标';
                }
                */
            },
            ai: {
                save: true,
                respondSha: true,
                respondShan: true,
                fireAttack: true,
                skillTagFilter: function (player) {
                    if (!game.players.some(function (current) {
                        return current != player &&
                            current.hasMark('DALF_mark_xuhuan') &&
                            current.countCards('h');
                    })) return false;
                },
                threaten: 1.2,
                order: 8.1,
                result: { player: 1 }
            },
            group: ["DALF_sumeng_onDoing"],
            subSkill: {
                fengyin: {
                    init: function (player, skill) {
                        player.addSkillBlocker(skill);
                    },
                    onremove: function (player, skill) {
                        player.removeSkillBlocker(skill);
                    },
                    skillBlocker: function (skill, player) {
                        return skill == 'DALF_sumeng';
                    },
                    mark: true,
                    marktext: "梦",
                    intro: {
                        name: "溯梦",
                        content: "〖溯梦〗本回合已失效"
                    },
                    sub: true
                },
                onDoing: {
                    charlotte: true,
                    trigger: {
                        player: ["useCardBefore", "respondBefore"]
                    },
                    forceOut: true,
                    firstDo: true,
                    forced: true,
                    silent: true,
                    popup: false,
                    filter: function (event, player) {
                        return event.skill == 'DALF_sumeng_backup';
                    },
                    content: function () {
                        "step 0"
                        trigger.includeOut = true;
                        event.players = game.filterPlayer(
                            current => current.hasMark('DALF_mark_xuhuan'),
                            null, true
                        ).sortBySeat(_status.currentPhase);
                        event.players.remove(player);
                        player.line(event.players, { color: [255, 182, 193] });
                        "step 1"
                        event.current = event.players.shift();
                        if (event.current.classList.contains('out')) {
                            game.broadcastAll(function (target) {
                                target.classList.remove('out');
                            }, event.current);
                            event.isOut = true;
                        } else event.isOut = false;
                        event.current.chooseCard({
                            filterCard(card, player) {
                                return get.name(card) == _status.event.getTrigger().card.name;
                            },
                            ai(card) {
                                if (_status.event.att < 0) return 0;
                                return 11 - get.value(card);
                            },
                            att: event.current.attitudeTo(
                                trigger.type == 'dying' ? trigger.dying : player),
                            prompt: get.translation('DALF_sumeng'),
                            prompt2: '你可以展示一张【' + get.translation(trigger.card.name) + '】令' +
                                get.translation(player) + (trigger.name == 'respond' ? '打出' : '使用') +
                                '之，然后你摸一张牌'
                        });
                        "step 2"
                        if (result.bool) {
                            player.line(event.current, { color: [255, 20, 147] });
                            event.current.showCards(result.cards, '溯梦回响－' + get.translation(event.current));
                            if (event.current != player)
                                event.current.$give(result.cards, player, false);
                            var namex = trigger.card.name;
                            trigger.card = result.cards[0];
                            trigger.cards = result.cards;
                            trigger.card.name = namex;
                            var ai = event.current.ai;
                            if (typeof ai.shown == 'number')
                                ai.shown = Math.min(ai.shown + 0.35, 0.95);
                            var next1 = event.current.draw();
                            event.next.remove(next1);
                            trigger.after.push(next1);
                            if (event.isOut) {
                                var next2 = game.createEvent('DALF_sumeng_re', false);
                                next2.set('player', event.current);
                                next2.setContent(function () {
                                    game.broadcastAll(function (target) {
                                        target.classList.add('out');
                                    }, player);
                                });
                                event.next.remove(next2);
                                trigger.after.push(next2);
                            }
                        } else {
                            event.current.popup('拒绝', 'fire');
                            if (event.isOut) {
                                game.broadcastAll(function (target) {
                                    target.classList.add('out');
                                }, event.current);
                            }
                            if (event.players.length) {
                                event.goto(1);
                            } else {
                                player.draw();
                                player.addTempSkill('DALF_sumeng_fengyin');
                                event.finish();
                                trigger.cancel();
                                trigger.getParent().goto(0);
                            }
                        }
                    },
                    sub: true
                }
            }
        },

        //或守鞠亚 & 或守鞠奈
        "DALF_chaosuan": {
            audio: "ext:约会大作战/audio:2",
            mod: {
                aiOrder(player, card, num) {
                    if (get.itemtype(card) == 'card' &&
                        card.hasGaintag('DALF_chaosuan'))
                        return num + 10;
                },
                aiValue(player, card, num) {
                    if (get.itemtype(card) == 'card' &&
                        card.hasGaintag('DALF_chaosuan'))
                        return num - 3;
                },
                aiUseful(player, card, num) {
                    if (get.itemtype(card) == 'card' &&
                        card.hasGaintag('DALF_chaosuan'))
                        return num + 3;
                }
            },
            init(player, skill) {
                player.storage['DALF_chaosuan'] = [setInterval(function () {
                    let cardx;
                    if (player.storage['DALF_chaosuan'])
                        cardx = player.storage['DALF_chaosuan'][1];
                    const bool = ui.cardPile.childElementCount == 0 ||
                        get.is.blocked('DALF_chaosuan', player);
                    if (cardx) {
                        if (bool) {
                            player.storage['DALF_chaosuan'][1] = null;
                            // if (get.is.singleHandcard() || lib.config.sort_card(cardx) > 0)
                            //     player.node.handcards1.removeChild(cardx);
                            // else
                            //     player.node.handcards2.removeChild(cardx);
                            game.broadcastAll((player, card) => {
                                if (!card._selfDestroyed) {
                                    card._selfDestroyed = true;
                                    card.fix();
                                    card.delete();
                                    card?.remove();
                                }
                            }, player, cardx);
                            ui.updatehl();
                        } else {
                            game.broadcastAll((card, cardx) => {
                                card.init(cardx);
                                card.storage.mapping = cardx;
                            }, cardx, ui.cardPile.firstChild);
                        }
                    } else if (!bool) {
                        game.broadcastAll((player, card, cardx) => {
                            card = ui.create.card(ui.special);
                            card.init(cardx);
                            card.storage.mapping = cardx;
                            player.storage['DALF_chaosuan'][1] = card;
                            player.directgains([card], null, 'DALF_chaosuan');
                        }, player, cardx, ui.cardPile.firstChild);
                    }
                }, 1000), null];
            },
            onremove(player, skill) {
                game.broadcast(function (player) {
                    clearInterval(player.storage[skill][0]);
                }, player);
            },
            trigger: {
                player: ["useCardBegin", "respondBegin"]
            },
            forced: true,
            filter: event => event.DALF_chaosuan,
            content() { },
            ai: { threaten: 1.7 },
            group: ["DALF_chaosuan_update", "DALF_chaosuan_refresh"],
            subSkill: {
                update: {
                    charlotte: true,
                    trigger: {
                        player: ["useCardBefore", "respondBefore", "loseBefore"]
                    },
                    forced: true,
                    silent: true,
                    priority: 5,
                    filter(event, player) {
                        return event.cards.some(cardx => {
                            return cardx.hasGaintag('DALF_chaosuan') &&
                                cardx.storage && cardx.storage.mapping;
                        });
                    },
                    async content(event, trigger, player) {
                        game.broadcastAll((player, trigger) => {
                            const cardx = player.storage['DALF_chaosuan'][1];
                            let p = trigger.cards.indexOf(cardx);
                            if (p != -1) trigger.cards[p] = cardx.storage.mapping;
                            if (trigger.name != 'lose' && trigger.cards.length == 1) {
                                trigger.card = get.autoViewAs(trigger.cards[0], trigger.cards);
                                trigger.DALF_chaosuan = true;
                            }
                            player.countCards('s', (c) => {
                                if (c.hasGaintag('DALF_chaosuan') && c != cardx) {
                                    if (!c._selfDestroyed) {
                                        c._selfDestroyed = true;
                                        c.fix();
                                        c.delete();
                                        c?.remove();
                                    }
                                }
                            });
                        }, player, trigger);
                    },
                    sub: true
                },
                refresh: {
                    charlotte: true,
                    trigger: {
                        global: ["gainAfter", "loseAfter"]
                    },
                    forced: true,
                    silent: true,
                    priority: 5,
                    filter(event, player) {
                        if (ui.cardPile.childElementCount == 0) return false;
                        return player.storage['DALF_chaosuan'][1].storage.mapping !=
                            ui.cardPile.firstElementChild;
                    },
                    async content(event, trigger, player) {
                        game.broadcastAll((player) => {
                            const cardx = player.storage['DALF_chaosuan'][1];
                            cardx.init(ui.cardPile.firstChild);
                            cardx.storage.mapping = ui.cardPile.firstElementChild;
                        }, player);
                    },
                    sub: true
                }
            }
        },
        "DALF_guizheng": {
            audio: 'ext:约会大作战/audio:2',
            enable: 'phaseUse',
            filter(event, player) {
                return player.countDiscardableCards('he') >=
                    (player.getStat('skill')['DALF_guizheng'] || 0);
            },
            filterCard(card, player, event) {
                return (player.getStat('skill')['DALF_guizheng']) ? true : false;
            },
            selectCard() {
                const num = get.player().getStat('skill')['DALF_guizheng'] || 0;
                return num > 0 ? num : -1;
            },
            position: 'he',
            check(card) {
                return 6.8 - get.value(card);
            },
            filterTarget(card, player, target) {
                return target != player && target.countCards('h') > 0;
            },
            async content(event, trigger, player) {
                const result = await event.target.chooseCard()
                    .set('position', 'h')
                    .set('forced', true)
                    .set('filterCard', (card, player) => {
                        return player.canRecast(card, player);
                    })
                    .set('ai', card => {
                        return 20 - get.value(card);
                    })
                    .set('prompt', '椝整')
                    .set('prompt2', '选择一张手牌，重铸之')
                    .forResult();
                if (result.bool) {
                    event.target.recast(result.cards);
                }
            },
            ai: {
                order: 1,
                result: {
                    player(player, target) {
                        if (player.hasSkill('DALF_chaosuan')) {
                            const card = player.storage['DALF_chaosuan'][1];
                            if (player.hasUseTarget(card, true, true))
                                return -10;
                        }
                        return 0;
                    },
                    target(player, target) {
                        if (player.hasSkill('DALF_chaosuan')) {
                            const card = player.storage['DALF_chaosuan'][1];
                            if (get.value(card) > 3) return target.countCards('h');
                            return -target.countCards('h');
                        }
                        return 1;
                    }
                }
            }
        },
        "DALF_hairu": {
            audio: "ext:约会大作战/audio:2",
            marktext: "骇",
            intro: {
                name: "骇入",
                mark(dialog, storage, player) {
                    dialog.add(storage);
                },
                markcount(storage, player) {
                    return storage.length;
                }
            },
            init(player, skill) {
                if (!player.storage[skill])
                    player.storage[skill] = [];
            },
            enable: "phaseUse",
            usable: 1,
            filterTarget(card, player, target) {
                return target.countCards('h');
            },
            selectTarget: [1, Infinity],
            async content(event, trigger, player) {
                const storage = player.storage[event.name] || [];
                if (event.target.hasCard(cardx => {
                    return !storage.includes(cardx);
                }, 'h')) {
                    const result = await player
                        .choosePlayerCard(
                            event.target, 'h', true)
                        .set('visible', true)
                        .set('ai', button => {
                            if (storage.includes(button.link))
                                return 0;
                            return get.useful(button.link) +
                                Math.random() * 3;
                        })
                        .set('prompt', get.translation(event.name))
                        .set('prompt2', '记录' + get.translation(event.target) +
                            '的一张手牌为「骇入」牌。')
                        .forResult();
                    if (result.bool) {
                        storage.addArray(result.cards);
                        event.target.addGaintag(result.cards, 'DALF_hairu');
                    }
                    player.markSkill(event.name);
                }
            },
            ai: {
                threaten: 1.5,
                order: 11,
                result: { target: -1 }
            },
            group: ["DALF_hairu_mark"],
            subSkill: {
                mark: {
                    charlotte: true,
                    trigger: { global: "gainAfter" },
                    forced: true,
                    silent: true,
                    filter(event, player) {
                        const storage = player.storage['DALF_hairu'];
                        return event.cards.some(cardx => {
                            return storage.includes(cardx);
                        });
                    },
                    async content(event, trigger, player) {
                        const storage = player.storage['DALF_hairu'];
                        const cards = trigger.cards.filter(
                            cardx => {
                                return storage.includes(cardx) &&
                                    get.position(cardx) == 'h';
                            });
                        if (cards.length)
                            trigger.player.addGaintag(cards, 'DALF_hairu');
                    },
                    sub: true
                }
            }
        },
        "DALF_moshu": {
            audio: "ext:约会大作战/audio:2",
            trigger: { global: "useCard" },
            forced: true,
            filter(event, player) {
                if (event.player == player) return false;
                const storage = player.storage['DALF_hairu'];
                if (event.DALF_moshu)
                    return event.player.hasCard(cardx => {
                        return storage.includes(cardx);
                    }, 'h');
                return event.cards.some(cardx => {
                    return storage.includes(cardx);
                });
            },
            async content(event, trigger, player) {
                const storage = player.storage['DALF_hairu'];
                if (trigger.DALF_moshu) {
                    const target = trigger.player;
                    const cards = target.getGainableCards(
                        player, 'h', cardx => {
                            return storage.includes(cardx);
                        }
                    );
                    if (cards.length)
                        await player.gain(cards, target, 'bySelf', 'giveAuto');
                    if (_status.currentPhase == target) {
                        trigger.cancel();
                        target.getHistory().useCard.remove(trigger);
                        game.getGlobalHistory().useCard.remove(trigger);
                        if (trigger.addCount !== false) {
                            const stat = target.getStat().card;
                            if (stat && stat[trigger.card.name] &&
                                typeof stat[trigger.card.name] == 'number'
                            ) stat[trigger.card.name]--;
                        }
                        game.log(trigger.player, '使用的', trigger.card, '作废了');
                    }
                } else {
                    trigger.excluded.add(player);
                    const len = ui.cardPile.childElementCount;
                    let p1 = Math.floor(Math.random() * len),
                        p2 = Math.floor(Math.random() * len),
                        p3 = Math.floor(Math.random() * len);
                    storage.add(ui.cardPile.childNodes[p1]);
                    if (p2 == p1) p2++;
                    storage.add(ui.cardPile.childNodes[p2]);
                    if (p3 == p1) p3++;
                    if (p3 == p2) p3++;
                    storage.add(ui.cardPile.childNodes[p3]);
                    player.markSkill('DALF_hairu');
                }
            },
            ai: {
                combo: "DALF_hairu",
                threaten: 1.5,
                effect: {
                    target: function (card, source, player) {
                        if (source == player) return;
                        const storage = player.storage['DALF_hairu'] || [];
                        if (storage.includes(card)) return [0.25, 0];
                        if (card.cards && card.cards.some(cardx => {
                            return storage.includes(cardx);
                        })) return [0.25, 0];
                    }
                }
            },
            global: ["DALF_moshu_ai"],
            group: ["DALF_moshu_check"],
            subSkill: {
                check: {
                    charlotte: true,
                    trigger: { global: "useCardBefore" },
                    forced: true,
                    silent: true,
                    priority: 5,
                    filter(event, player) {
                        const storage = player.storage['DALF_hairu'];
                        if (event.player != player &&
                            !event.cards.some(cardx => {
                                return storage.includes(cardx) ||
                                    get.position(cardx) != 'h';
                            })
                        ) event.DALF_moshu = true;
                        return false;
                    },
                    sub: true
                },
                ai: {
                    charlotte: true,
                    mod: {
                        aiOrder(player, card, num) {
                            if (get.itemtype(card) == 'card' &&
                                card.hasGaintag('DALF_hairu'))
                                return num + 10;
                        },
                        aiValue(player, card, num) {
                            if (get.itemtype(card) == 'card' &&
                                card.hasGaintag('DALF_hairu'))
                                return num > 1 ? Math.max(1, num - 3) : (num - 3);
                        }
                    },
                    ai: {
                        effect: {
                            player_use(card, player, target) {
                                if (get.itemtype(card) == 'card' &&
                                    card.hasGaintag('DALF_hairu')) return [1, 1.2];
                            }
                        }
                    },
                    sub: true
                }
            }
        },

        /*崇宫真那*/
        "DALF_yingfen": {
            audio: "ext:约会大作战/audio:2",
            mod: {
                globalFrom: function (from, to, distance) {
                    var num = Math.max(from.getDamagedHp() - to.getDamagedHp(), 0);
                    return distance - num;
                },
                maxHandcard: function (player, num) {
                    if (player.hp == 1) return num + 3;
                }
            },
            trigger: {
                player: "changeHp",
            },
            forced: true,
            filter: function (event, player) {
                return event.num < 0 && player.hp == 1;
            },
            content: function () { }
        },
        "DALF_jiqiang": {
            audio: "ext:约会大作战/audio:2",
            trigger: {
                global: "phaseJieshu"
            },
            forced: true,
            filter: function (event, player) {
                return player.countCards('h') < player.getHandcardLimit();
            },
            content: function () {
                "step 0"
                player.loseHp();
                "step 1"
                player.drawTo(player.maxHp);
            },
            ai: {
                threaten: 0.8,
                effect: {
                    target: function (card, source, player) {
                        if (player.hp > 1) return;
                        if (source != player && get.tag(card, 'loseCard')) {
                            return [1, -1];
                        }
                    }
                }
            }
        },
        "DALF_congyun": {
            audio: "ext:约会大作战/audio:2",
            trigger: {
                player: "shaMiss",
                target: "shaMiss"
            },
            direct: true,
            filter: function (event, player) {
                return player.countCards('he');
            },
            content: function () {
                "step 0"
                var next = player.chooseToDiscard();
                next.set('filterCard', function (card) {
                    return get.type(card) != 'basic';
                });
                next.set('ai', function (card) {
                    if (_status.event.player.isHealthy()) return 0;
                    return 7 - get.value(card);
                });
                next.set('prompt', get.prompt('DALF_congyun'));
                next.set('prompt2', '弃置一张非基本牌，以回复一点体力');
                next.set('logSkill', 'DALF_congyun');
                "step 1"
                if (result.bool) {
                    player.recover();
                }
            }
        },

        /*尼别科尔*/
        // "DALF_qianye_info": "锁定技，你跳过弃牌阶段；游戏开始时，你获得角色数张【影】。" +
        //     "<br>当你回复体力时，防止之并获得两张【影】。" +
        //     "<br>你的回合内，当一张红色牌进入弃牌堆时，你获得一张【影】。",
        "DALF_qianye": {
            audio: "ext:约会大作战/audio:3",
            trigger: {
                player: ["enterGame", "phaseDiscardBefore", "recoverBefore"],
                global: ["phaseBefore", "loseAfter", "cardsDiscardAfter", "loseAsyncAfter", "equipAfter"]
            },
            forced: true,
            filter: function (event, player, triggername) {
                if (triggername == 'enterGame') return true;
                if (event.name == 'phase') return game.phaseNumber == 0;
                if (event.name == 'phaseDiscard') return true;
                if (event.name == 'recover') return true;
                if (_status.currentPhase != player) return false;
                return event.cards.some(card => {
                    return get.color(card) == 'red' && get.position(card, true) == 'd';
                });
            },
            async content(event, trigger, player) {
                if (trigger.name == 'phaseDiscard') {
                    trigger.cancel();
                    game.log(player, '跳过了', '#y弃牌阶段');
                } else if (trigger.name == 'phase' || event.triggername == 'enterGame') {
                    const num = game.players.length;
                    await player.gain(lib.card.ying.getYing(num), 'gain');
                } else if (trigger.name == 'recover') {
                    trigger.cancel();
                    if (lib.config.background_audio) {
                        game.playAudio('effect', 'recover');
                    }
                    game.broadcast(() => {
                        if (lib.config.background_audio) {
                            game.playAudio('effect', 'recover');
                        }
                    });
                    player.$damagepop('<b>⨉</b>', 'wood');
                    await player.gain(lib.card.ying.getYing(2), 'gain');
                } else {
                    const num = trigger.cards.filter(card => {
                        return get.color(card) == 'red' && get.position(card) == 'd';
                    });
                    await player.gain(lib.card.ying.getYing(num), 'gain');
                }
            }
        },
        // "DALF_buxi_info": "锁定技，当你受到伤害时，防止之，伤害来源弃置你伤害值两倍的手牌。" +
        //     "<br>若你失去手牌中所有【影】，你进入濒死状态；否则防止你处于濒死状态。",
        "DALF_buxi": {
            audio: "ext:约会大作战/audio:2",
            mod: {
                aiValue(player, card, num) {
                    if (get.name(card) == 'ying')
                        return num + 20 / player.countCards('h', 'ying');
                }
            },
            trigger: {
                player: ["loseAfter", "damageBegin4", "dying"],
                global: ["equipAfter", "addJudgeAfter", "gainAfter", "loseAsyncAfter", "addToExpansionAfter"],
            },
            forced: true,
            filter(event, player) {
                if (event.name == 'damage') return true;
                if (player.countCards('h', card => {
                    return get.name(card) == 'ying';
                })) {
                    player.nodying = true;
                    game.broadcast((player) => {
                        player.nodying = true;
                    }, player);
                    return false;
                } else {
                    player.nodying = false;
                    game.broadcast((player) => {
                        player.nodying = false;
                    }, player);
                }
                const evt = event.getl(player);
                return evt && evt.player == player &&
                    evt.hs && evt.hs.length > 0;
            },
            async content(event, trigger, player) {
                if (trigger.name == 'damage') {
                    trigger.cancel();
                    if (get.itemtype(trigger.source) == 'player') {
                        await trigger.source.discardPlayerCard()
                            .set('selectButton', trigger.num * 2)
                            .set('position', 'h')
                            .set('target', player)
                            .set('prompt', '不息')
                            .set('prompt2', '弃置' + get.translation(player) +
                                get.cnNumber(trigger.num * 2) + '张手牌');
                    } else if (trigger.name != 'dying') {
                        player.dying();
                    }
                }
            },
        },
        // "DALF_shenshi_info": "出牌阶段各限一次，你可以将一张黑色手牌当〔刺【杀】/【过河拆桥】〕使用。",
        "DALF_shenshi": {
            audio: "ext:约会大作战/audio:2",
            enable: "phaseUse",
            filter(event, player) {
                if (!player.hasCard({ color: 'black' }, 'hs')) return false;
                const stat = player.getStat('skill');
                return !stat.DALF_shenshi_sha || !stat.DALF_shenshi_guohe;
            },
            chooseButton: {
                dialog(event, player) {
                    var list = [];
                    const stat = player.getStat('skill');
                    if (!stat.DALF_shenshi_sha)
                        list.push(['basic', '', 'sha', 'stab']);
                    if (!stat.DALF_shenshi_guohe)
                        list.push(['trick', '', 'guohe']);
                    return ui.create.dialog('神蚀', [list, 'vcard']);
                },
                check(button) {
                    return get.player().getUseValue(
                        { name: button.link[2], nature: button.link[3] },
                        true, true
                    );
                },
                filter(button) {
                    return _status.event.getParent().filterCard(get.autoViewAs(
                        { name: button.link[2], nature: button.link[3] }, 'unsure'
                    ), _status.event.player, _status.event);
                },
                backup(links, player) {
                    return {
                        popname: true,
                        filterCard(card, player) {
                            return get.color(card) == 'black';
                        },
                        position: 'hs',
                        viewAs: {
                            name: links[0][2],
                            nature: links[0][3]
                        },
                        check(card) {
                            return 7 - get.value(card);
                        },
                        onuse(event, player) {
                            let stat = player.getStat('skill');
                            const skillname = 'DALF_shenshi_' + event.card.name;
                            if (!stat[skillname]) stat[skillname] = 1;
                            else stat[skillname]++;
                        }
                    };
                },
                prompt(links, player) {
                    return '将一张黑色手牌当' + get.translation(links[0][3]) +
                        '【' + get.translation(links[0][2]) + '】使用';
                }
            },
            ai: {
                order(item, player) {
                    if (!player.getStat('skill').DALF_shenshi_guohe)
                        return get.order({ name: 'guohe' }) - 0.15;
                    return get.order({ name: 'sha' }) - 0.3;
                },
                result: {
                    player: 1
                }
            }
        },
    }
}